
var express 	= require('express');
//环境变量
var env 		= process.env.NODE_ENV || 'development';
//服务器配置
var config 		= require('./config/config')[env];

//链接MongoDB
var mongoose 	= require('mongoose');

console.log('config.db' + config.db+'/ucsdb');

mongoose.connect(config.db+'/ucsdb');

//导入数据库models
var fs 			= require('fs');
fs.readdirSync(__dirname + '/app/model').forEach(function (file){
    if (~file.indexOf('.js')) require(__dirname + '/app/model/' + file);
});

//配置express
var app = express();
require('./config/express')(app, config);

//配置路由
require('./routes/routes')(app);

//错误处理
app.use(function (err, req, res, next) {

    var meta = '[' + new Date() + '] ' + req.url + '\n';

    console.error(meta + err.stack + '\n');

    res.status(500).end('500 not found'+meta);

});

app.use(function (req, res, next) {

    var meta = '[' + new Date() + '] ' + req.url + '\n';
    console.error(meta + '404 Not Found' + '\n');
    res.status(404).end('404 not found'+meta+'\n');

});

module.exports = app;